package dbms.query;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dbms.absyn.ConditionList;

public class SelectPlan extends Plan{
	
	public ConditionList conditionList;
	
	public ResultSet resultSet;
	
	public SelectPlan (ConditionList conditionList){
		this.conditionList = conditionList;
	}
	
	public SelectPlan (ResultSet resultSet) {
		this.resultSet = resultSet;
	}

	public ResultSet execute(ResultSet resultSet) {
		
		if (resultSet != null) {
			Map<String, List<Object>> oldResult = resultSet.resultSet;
			Map<String, List<Object>> result = resultSet.resultSet;
			for (String str : oldResult.keySet()) {
				if (!result.containsKey(str)) oldResult.remove(str);  
			}
			return resultSet;
		}
		
			
		boolean flag[] = new boolean[100];
		Arrays.fill(flag, false);
		Map<String, List<Object>> oldResult = resultSet.resultSet;
		Map<String, List<Object>> result = new HashMap<String, List<Object>>();
		List<String> FieldList = resultSet.fieldList;
		List<Object> temp = oldResult.get(FieldList.get(0));
		int line;
		if (temp == null) 
			line = 0;
		else
			line = temp.size();

		
		List<String> attrList = new ArrayList<String>();
		ConditionList cl = conditionList;
		while (cl != null) {
			if (cl.condition.attr1 != null) {
				attrList.add(cl.condition.attr1.attr.name);
				attrList.add(cl.condition.attr2.attr.name);
			}
			else {
				attrList.add(cl.condition.attr.attr.name);	
			}
			cl = cl.next;
		}

		for (int i = 0; i < line; i++) {
			List<Object> DataList = new ArrayList<Object>();
			int n = attrList.size();
			for (int j = 0; j < n; j++) {
				String attr = attrList.get(j);
				DataList.add(oldResult.get(attr).get(i));
			}
			if (conditionList.satisfy(attrList, DataList)) {
				flag[i] = true;
			}
		}
		for (String attr : FieldList) {
			temp = oldResult.get(attr);
			for (int i = line-1; i >= 0; i--)
				if (!flag[i]) temp.remove(i);
			result.put(attr, temp);
		}
		
		return new ResultSet(result);
	}

}
